/********************************************************/
/*	Copyright (C) 2012 Gong Li Bin			*/
/*	Project:	MapReduce			*/
/*	Author:		gong_libin			*/
/*	Date:		2013_05_25			*/
/*	File:		MrHubSel.cpp			*/
/********************************************************/

#include "MrHub.h"

#define	MR_HS_TOTAL			10
#define	MR_HS_PACKET			MR_PACKET * 100

int main(int argc, char* argv[])
{
	CMrTcp CTcp;
	CMrTime CTime;
	int iCount = 1;
	int iLength = 0;
	CMrPro CProSend;
	CMrPro CProRecv;
	char szKey[MR_HS_PACKET] = { 0 };
	char szVal[MR_HS_PACKET] = { 0 };
	UCHAR uszSend[MR_HS_PACKET] = { 0 };
	UCHAR uszRecv[MR_HS_PACKET] = { 0 };
	MRPROKV_S stRecv[MR_MR_VAL];
	MRPROKV_S stSend = {MR_MR_KEY, 0, (UCHAR*)szKey};
	MRPROHEAD_S stHead = {
		MR_PRO_FLAG,
		MR_PRO_1,
		MR_PRO_DATA,
		MR_PRO_0,
		MR_PRO_Y,
		MR_PRO_0,
		MR_DEF_EHUB,
		MR_DEF_SELT,
		MR_PRO_0,
		MR_DEF_SUCC,
		MR_MR_KEY,
		MR_PRO_0,
	};

	CTime.MrTimeOn();

	for (; iCount < MR_HS_TOTAL; iCount ++) {
		sprintf(szKey, "%d", iCount);
		stSend.m_iLength = strlen(szKey);

		CProSend.MrProPutBody(NULL);
		CProSend.MrProInduce(&stHead);
		CProSend.MrProPutLength(MrProKvOutput(&stSend, MR_MR_KEY, &uszSend[MR_PRO_HEAD], MR_HS_PACKET - MR_PRO_HEAD));
		CProSend.MrProCreate(uszSend, MR_HS_PACKET);

		if (MR_SUCCESS == CTcp.MrTcpConnect((char*)"172.16.8.211", (char*)"12001")) {
			CTcp.MrTcpSetLinger(0);
			CTcp.MrTcpSetNoDelay();
			if (CTcp.MrNetSend(uszSend, MR_PRO_HEAD + CProSend.MrProGetLength()) > 0) {
				memset(uszRecv, '\0', MR_HS_PACKET);
				if (MR_PRO_HEAD == CTcp.MrNetRecv(uszRecv, MR_PRO_HEAD)) {
					CProRecv.MrProReset();
					CProRecv.MrProParse(uszRecv, MR_PRO_HEAD);
					CProRecv.MrProDisplay();
					if (CProRecv.MrProGetLength() > 0) {
						iLength = CTcp.MrNetRecvAll(&uszRecv[MR_PRO_HEAD], CProRecv.MrProGetLength());
						if (iLength == CProRecv.MrProGetLength()) {
							memset(stRecv, '\0', sizeof(MRPROKV_S) * MR_MR_VAL);
							MrProKvInput(stRecv, MR_MR_VAL, &uszRecv[MR_PRO_HEAD], iLength);
							memcpy(szVal, stRecv[1].m_puszValue, stRecv[1].m_iLength);
							MR_PRINT("Key[%08d] -> %s\n", iCount, szVal);
						}
						else {
							MR_ERROR("Failed[%08d] to MrNetRecv\n", iCount);
						}
					}
					else {
						MR_PRINT("Key[%08d] %s not found\n", iCount, szKey);
					}
				}
				else {
					MR_ERROR("Failed[%08d] to MrNetRecv\n", iCount);
				}
			}
			else {
				MR_ERROR("Failed[%08d] to MrNetSend\n", iCount);
			}
			CTcp.MrNetClose();
		}
		else {
			MR_ERROR("Failed[%08d] to MrTcpConnect\n", iCount);
		}
	}

	CTime.MrTimeOff();
	CTime.MrTimeDisplay();

	return MR_SUCCESS;
}
